﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SmoothFollow : MonoBehaviour {


    // 跟随目标
    [SerializeField]
    public Transform target;
    // 相机距离
    [SerializeField]
    private float distance = 10.0f;
    // 相机高度
    [SerializeField]
    private float height = 5.0f;

    [SerializeField]
    private float rotationDamping;
    [SerializeField]
    private float heightDamping;

    // Use this for initialization
    void Start() { }

    // Update is called once per frame
    void LateUpdate()
    {
        if (!target)
            return;

        // 计算当前旋转角度
        var wantedRotationAngle = target.eulerAngles.y;
        var wantedHeight = target.position.y + height;

        var currentRotationAngle = transform.eulerAngles.y;
        var currentHeight = transform.position.y;

        // 计算旋转角度
        currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);

        //计算相机高度
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

        // 角度实例化
        var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

        // 更新距离
        transform.position = target.position;
        transform.position -= currentRotation * Vector3.forward * distance;

        // 更新位置
        transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);

        transform.LookAt(target);
    }
}
